package c15;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;

/*
    同步容器虽然给容器加上了锁，还是会存在一些场景有同步问题，
    比如说复合操作：先检查，后修改
    伪同步
    迭代

 */
public class SynchronizedCollectionDemo {
    static volatile boolean flag = true;

    public static void main(String[] args) throws FileNotFoundException {
        final List<String> synchronizedList = Collections.synchronizedList(new ArrayList<String>());
        PrintStream printStream = new PrintStream(new FileOutputStream("result.txt"));
        Thread modifyThread = new Thread(()->{
            for (int i = 0; i < 100; i++) {
                synchronizedList.add("item-" + i);
                printStream.println("add:"+i);
                System.out.println("add:"+i);

                try {
                    Thread.sleep((int)Math.random()*10);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            flag = false;
        });
        Thread iteratorThread = new Thread(() -> {
            while(flag) {
                synchronized (synchronizedList) {
                    printStream.println("enter");
                    try {
                        Thread.sleep((int) Math.random());
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    for (String item : synchronizedList) {
                        System.out.println(item);
                        printStream.println(item);
                    }
                }
            }
        });
        modifyThread.start();
        iteratorThread.start();

    }
}
